package com.atguigu.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.baservice.exceptionhandler.GuliException;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.service.EduSubjectService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;


public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {
    private EduSubjectService eduSubjectService;

    public SubjectExcelListener() {
    }

    public SubjectExcelListener(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }

    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if(subjectData==null){
            throw new GuliException(20001,"文件数据为空");
        }
        EduSubject existOneSubject=this.existOneSubject(eduSubjectService,subjectData.getOneSubjectName());
        if (existOneSubject==null){
            existOneSubject =new EduSubject();
            existOneSubject.setParentId("0");
            existOneSubject.setTitle(subjectData.getOneSubjectName());
            eduSubjectService.save(existOneSubject);
        }
        String pid= existOneSubject.getId();
        EduSubject existwoSubject=this.existwoSubject(eduSubjectService,subjectData.getOneSubjectName(),pid);
        if(existwoSubject==null){
            existwoSubject =new EduSubject();
            existwoSubject.setParentId(pid);
            existwoSubject.setTitle(subjectData.getTwoSubjectName());
            eduSubjectService.save(existwoSubject);
        }
    }
    public EduSubject existOneSubject(EduSubjectService eduSubjectService,String name){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",0);
        EduSubject onesubject = eduSubjectService.getOne(wrapper);
        return onesubject;
    }
    public EduSubject existwoSubject(EduSubjectService eduSubjectService,String name,String pid){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        EduSubject twosubject = eduSubjectService.getOne(wrapper);
        return twosubject;
    }
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
